package china.z.console.module.controller.login;

import china.z.console.common.exception.CustomException;
import china.z.console.common.util.MD5Util;
import china.z.console.data.entity.AcctUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class LoginController {

    /**
     * 登陆
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "/login";
    }

    /**
     * 验证
     * @param request
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String submit(HttpServletRequest request,String username,String password){
        //添加用户认证信息
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
       try{
           //进行验证，这里可以捕获异常，然后返回对应信息
           subject.login(usernamePasswordToken);
           AcctUser acctUser= (AcctUser) subject.getPrincipal();
           return "redirect:/index";
       }catch (IncorrectCredentialsException e) {
           throw new CustomException("登陆密码错误");
       } catch (Exception e) {
           throw new CustomException("账号异常");
       }
    }

    /**
     * 退出
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        return "redirect:/login";
    }

}
